package com.richapp.launcher.database.system;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;

import java.util.ArrayList;
import java.util.List;

public class SystemBaseDao<T>{

	private Context context;
	private SystemDatabaseHelper helper = null;
	private Dao<T,Integer> tOp = null;

	public SystemBaseDao(Context context, Class<T> tClass) {
		this.context = context;
		try {
			helper = SystemDatabaseHelper.getHelper(this.context);
			tOp = helper.getDao(tClass);
		} catch (Exception e) {
			Log.e(getClass().getName(),e.getMessage());
		}
	}
	
	public void add(T t){
		try {
			tOp.createOrUpdate(t);
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
	}

	public void del(T t){
		try {
			tOp.delete(t);
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
	}

	public void delAll(){
		try {
			tOp.delete(tOp.queryForAll());
		}catch (Exception e){
			Log.e(getClass().getName(), e.getMessage());
		}
	}

	public void delBy(String columnName, Object value){
		try {
			tOp.delete(tOp.queryBuilder().where().eq(columnName,value).query());
		}catch (Exception e){
			Log.e(getClass().getName(), e.getMessage());
		}
	}

	public T getFirst(){
		T t = null;
		try {
			t = tOp.queryBuilder().queryForFirst();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return t;
	}

	public List<T> getAll(){
		List<T> list = new ArrayList<T>();
		try {
			list = tOp.queryBuilder().query();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return list;
	}

	public List<T> getAllOrderBy(String name,boolean asc){
		List<T> list = new ArrayList<T>();
		try {
			list = tOp.queryBuilder().orderBy(name,asc).query();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return list;
	}

	public Dao<T, Integer> gettOp() {
		return tOp;
	}
}
